package com.atguigu.gmall.seckill.schedule;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.seckill.entity.SeckillGoods;
import com.atguigu.gmall.seckill.service.SeckillGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lhh
 * @ClassName SeckillGoodsUpService
 * @date 2022 2022/12/29
 */

@Slf4j
@Service
public class SeckillGoodsUpService {

    @Resource
    SeckillGoodsService seckillGoodsService;

    @Autowired
    StringRedisTemplate redisTemplate;

    //秒 分  时  日  月  周
    @Scheduled(cron = "0 0 2 * * ?")
    //@Scheduled(cron = "0 * * * * ?")
    public void upGoods(){
        log.info("定时任务上架每天的秒杀商品");
        //格式化当天的时间格式
        String formatDate = DateUtil.formatDate(new Date());
        //查询当天秒杀的商品
        List<SeckillGoods> seckillGoods = seckillGoodsService.getSeckillGoodsByDayFromCache(formatDate);
        //将查询到的数据存入缓存
        String cacheKey= RedisConst.SECKILL_GOODS_CACHE+formatDate;

        for (SeckillGoods goods : seckillGoods) {
            redisTemplate.opsForHash().put(cacheKey,goods.getSkuId().toString(), JSON.toJSONString(goods));
        }
        //设置过期时间
        redisTemplate.expire(cacheKey,2, TimeUnit.DAYS);

        //把当天秒杀的商品在本地缓存中保存
        seckillGoodsService.saveToLocalCache(seckillGoods);
    }
}
